<?php

namespace App\Http\Controllers\Api\Message;

use App\Http\Requests\Api\Message\MessageInitRequest;
use App\Http\Requests\Api\Message\MessageReadCallbackRequest;
use App\Http\Requests\Api\Message\MessageReadRequest;
use App\Http\Requests\Api\Message\MessageResetBusyRequest;
use App\Http\Requests\Api\Message\MessageSendRequest;
use App\Http\Requests\Api\Message\MessageStatusRequest;
use App\Http\Requests\Api\Message\MessageVideoCallbackRequest;
use App\Http\Requests\Api\Message\MessageVideoCallRequest;
use App\Models\Record;
use App\Models\Stranger;
use App\Models\User;
use GatewayClient\Gateway;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Http\Controllers\Api\Message\RtcTokenBuilder;
use DateTime;
use DateTimeZone;

class GatewayEventsController extends Controller
{
    public function __construct()
    {
        Gateway::$registerAddress = '127.0.0.1:1238';

    }

    public function init(MessageInitRequest $request)
    {
        $user = Auth::guard('api')->user();
        if(!$user){abort(401);}
        $uid = $user->id;
        $client_id = $request->input("client_id");
        Gateway::bindUid($client_id, $uid);
        // 获取它的所有朋友的id
        $friendsAll = Stranger::where([
            ['user_id', $uid],
        ])->pluck('stranger_id');
        $online_message = [
            'type' => 'online',
            'data' => [
                'id' => (int)$uid,
            ]
        ];
        if (!empty($friendsAll)) {
            foreach ($friendsAll as $vo) {
                $user_client_id = Gateway::getClientIdByUid($vo);
                if (!empty($user_client_id)) {
                    Gateway::sendToUid($vo, json_encode($online_message));
                }
            }
        }
        /*$ret = $user->groups;
        if (!$ret->isEmpty()) {
            foreach ($ret as $key => $vo) {
                Gateway::joinGroup($client_id, $vo->id);  //将登录用户加入群组
            }
        }
        unset($ret);*/
        $this->sendNotice($uid, "初始化成功！");
        $user->online = 1;
        if(!$user->save()){
            abort(500);
        }
        return response()->json([
            'code' => 0,
            'message' => '初始化消息响应',
        ]);
    }

    public function send(MessageSendRequest  $request)
    {
        $user = Auth::guard('api')->user();
        if(!$user){abort(401);}
        // 聊天消息
        $to_id = $request->input("to_id");
        $type = $request->input("type");
        $content = $request->input("content");
        $uuid = $request->input("uuid");
        $thumbnail = $request->input("thumbnail");
        $length = $request->input("length");
        $excerpt = Str::limit($content, 100);
        $chat_message = [
            'type' => 'chatMessage',
            'data' => [
                'window_id' => $user->id,
                'content' => htmlspecialchars($content),
                'type' => $type,
                'uuid' => $uuid,
                'thumbnail' => $thumbnail,
                'length' => $length,

            ]
        ];

        // 加入聊天log表
        $param = [
            'from_id' => (int)$user->id,
            'to_id' => (int)$to_id,
            'content' => htmlspecialchars($content),
            'status' => 1,
            'type' => $type,
            'read' => 0,
            'uuid' => $uuid,
            'thumbnail' => $thumbnail,
            'length' => $length,
        ];
        if (empty(Gateway::getClientIdByUid($to_id))) {
            $param['push'] = 1;  //用户不在线,标记此消息推送
            /*$system =[
                'type' => 'chatMessage',
                'data' => [
                    'type' => 'system' //系统消息
                    ,'window_id' => (int)$to_id //聊天窗口ID
                    ,'content' => '对方已掉线'
                ]
            ];
            Gateway::sendToUid($user->id, json_encode($system));*/
        }
        $post = Record::create($param);
        if($request->input("timestamp")){
            $dateParam = [
                'from_id' => (int)$user->id,
                'to_id' => (int)$to_id,
                'content' => htmlspecialchars($content),
                'status' => 1,
                'type' => "date",
                'read' => 1,
                'uuid' => "0",
            ];
            Record::create($dateParam);
        }
        if ($post){
            Gateway::sendToUid($to_id, json_encode($chat_message));
            return response()->json([
                'code' => 0,
                'message' => '发送消息成功响应',
            ]);
        }else{
            abort(500);
        }

    }
    public function sendNotice($uid,$notice,$code = 0)
    {
        if (!empty(Gateway::getClientIdByUid($uid))) {
            $online_message = [
                'type' => "notice",
                'message' => "$notice",
                'data' => "",
                'code' => $code,
            ];
            Gateway::sendToUid($uid, json_encode($online_message));
        }
    }
    public function status(MessageStatusRequest $request)
    {
        $user = Auth::guard('api')->user();
        if(!$user){abort(401);}
        $uid = $user->id;
        $user->status = $request->input("status");
        if($user->save()){
            $this->sendNotice($uid , "更新状态成功！");
            // 获取它的所有会话的id
            $friendsAll = Stranger::where([
                ['user_id', $uid],
            ])->pluck('stranger_id');

            if (!empty($friendsAll)) {
                foreach ($friendsAll as $vo) {
                    $user_client_id = Gateway::getClientIdByUid($vo);
                    if (!empty($user_client_id)) {
                        $online_message = [
                            'type' => 'status',
                            'data' => [
                                'id' => $uid,
                                'status' => (int)$request->input("status")
                            ],
                        ];
                        Gateway::sendToUid($vo, json_encode($online_message));
                        return response()->json([
                            'code' => 0,
                            'message' => '更新用户状态成功响应',
                        ]);
                    }
                }
            }
        }else{
            $this->sendNotice($uid , "更新状态失败！",1);
            return response()->json([
                'code' => 0,
                'message' => '更新用户状态失败响应',
            ]);
        }
    }
    public function videoCall(MessageVideoCallRequest  $request)
    {
        $user = Auth::guard('api')->user();
        $window_id = $request->input('id');
        if (empty(Gateway::getClientIdByUid($window_id))) {
            abort(403,'对方不在线');
        }
        $stranger = User::find($window_id);
        /*if($stranger->busy == 1){
            abort(403,'对方占线');
        }
        $user->busy=1;

        $stranger->busy = 1;*/

        if((!$user->save()) || (!$stranger->save())){
            abort(500,"服务器错误");
        }
        $appID = "04ac2a2957c24c95bf9a49e8c9c9229e";
        $appCertificate = "329689be06774c6cb21c38092f60cb82";
        $channelName = $request->input('uuid');
        $uid = 0;
        $uidStr = "$window_id";
        $role = RtcTokenBuilder::RolePublisher;
        $expireTimeInSeconds = 3600;
        $currentTimestamp = (new DateTime("now", new DateTimeZone('UTC')))->getTimestamp();
        $privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;

        $token = RtcTokenBuilder::buildTokenWithUid($appID, $appCertificate, $channelName, $uid, $role, $privilegeExpiredTs);
        //echo 'Token with int uid: ' . $token . PHP_EOL;

        //$token = RtcTokenBuilder::buildTokenWithUserAccount($appID, $appCertificate, $channelName, $uidStr, $role, $privilegeExpiredTs);
        //echo 'Token with user account: ' . $token . PHP_EOL;
        $chat_message = [
            'type' => 'videoCall',
            'data' => [
                'window_id' => (int)$user->id,
                'token' => $token,
                'channel_name' =>  $channelName,
                'avatar' =>  $user->avatar,
                'nickname' =>  $user->nickname,
                'user_id' =>  (int)$stranger->id,
            ]
        ];
        Gateway::sendToUid($window_id, json_encode($chat_message));
        return response()->json([
            'code' => 0,
            'message' => '请求视频通话成功响应',
            'token' => $token,
            'channelName' => $channelName,
        ]);
    }

    /*public function resetBusy(MessageResetBusyRequest $request)
    {
        $user_1 = User::find($request->id_1);
        $user_1->busy = 0;
        $user_2 = User::find($request->id_2);
        $user_2->busy = 0;
        if((!$user_1->save()) || (!$user_2->save())){
            abort(500,"服务器错误");
        }else{
            return response()->json([
                'code' => 0,
                'message' => '重置用户忙线状态成功响应',
            ]);
        }
    }*/
    public function videoCallback(MessageVideoCallbackRequest $request)
    {
        /*
         * code 解释
         * 0 主动挂断
         * 1 占线
         * 2 拒接
         *
         */
        $window = $request->input('window');
        $user = Auth::guard('api')->user();
        $statusCode = $request->input('code');

        //默认情况下接收者为呼叫方
        $receiver = $window;
        //只有主动挂断，接收者才为被呼叫方
        /*if($statusCode == 0){
            $receiver = $user->id;
        }*/

        $chat_message = [
            'type' => 'videoCallback',
            'data' => [
                'window_id' => (int)$user->id,
                'status_code' => (int)$statusCode,
            ]
        ];
        if (empty(Gateway::getClientIdByUid($receiver))) {
            abort(200,'不需要回调');
        }else{
            Gateway::sendToUid($receiver, json_encode($chat_message));
        }
        return response()->json([
            'code' => 0,
            'message' => '请求视频回调成功响应',
        ]);
    }

    /*public function readCallBack(MessageReadCallbackRequest $request)
    {
        $receiver = $request->input('window');
        $chat_message = [
            'type' => 'readCallback',
            'data' => [
                'window_id' => (int)$receiver,
            ]
        ];
        if (empty(Gateway::getClientIdByUid($receiver))) {
            abort(200,'不需要回调');
        }else{
            Gateway::sendToUid($receiver, json_encode($chat_message));
        }
        return response()->json([
            'code' => 0,
            'message' => '已读消息回调成功响应',
        ]);
    }*/
    public function read(MessageReadRequest $request)
    {
        $user = Auth::guard('api')->user();
        $window_id = $request->input("id");
        Record::where("from_id",$window_id)->where("to_id",$user->id)->update(['read' => 1]);
        $chat_message = [
            'type' => 'readCallback',
            'data' => [
                'window_id' => (int)$user->id
            ]
        ];
        if (empty(Gateway::getClientIdByUid($window_id))) {
            abort(200,'不需要回调');
        }else{
            Gateway::sendToUid($window_id, json_encode($chat_message));
        }
        return response()->json([
            'code' => 0,
            'message' => '已读消息回调成功响应',
        ]);
    }
}
